import logging
from logging.handlers import RotatingFileHandler
import os
from datetime import datetime
import shutil

class LogManager:
    def __init__(self, log_dir='src/logs/'):
        self.log_dir = log_dir
        self._setup_logging()
        self._cleanup_old_logs()

    def _setup_logging(self):
        """配置日志格式和输出"""
        # 创建日志目录
        today = datetime.now().strftime('%Y-%m-%d')
        daily_dir = os.path.join(self.log_dir, today)
        os.makedirs(daily_dir, exist_ok=True)

        # 日志格式
        log_format = '%(asctime)s - %(levelname)s - %(message)s'
        
        # 配置info日志
        info_handler = RotatingFileHandler(
            os.path.join(daily_dir, 'info.log'),
            maxBytes=1 * 1024 * 1024 * 1024,  # 1GB
            backupCount=7
        )
        info_handler.setLevel(logging.INFO)
        info_handler.setFormatter(logging.Formatter(log_format))

        # 配置error日志
        error_handler = RotatingFileHandler(
            os.path.join(daily_dir, 'error.log'),
            maxBytes=1 * 1024 * 1024 * 1024,  # 1GB
            backupCount=7
        )
        error_handler.setLevel(logging.ERROR)
        error_handler.setFormatter(logging.Formatter(log_format))

        # 添加处理器
        self.logger = logging.getLogger('pet_ai')
        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(info_handler)
        self.logger.addHandler(error_handler)

    def _cleanup_old_logs(self):
        """清理旧日志文件"""
        # 获取所有日志目录
        log_dirs = [d for d in os.listdir(self.log_dir) 
                   if os.path.isdir(os.path.join(self.log_dir, d))]
        
        # 保留最近7天的日志
        log_dirs.sort(reverse=True)
        for old_dir in log_dirs[7:]:
            shutil.rmtree(os.path.join(self.log_dir, old_dir))

    def info(self, message):
        """记录info日志"""
        self.logger.info(message)

    def error(self, message):
        """记录error日志"""
        self.logger.error(message)
